const express = require('express');
const router = express.Router();

const Movie = require('../models/movie');
const User = require('../models/user');
const Comment = require('../models/comment');
const Article = require('../models/article');
const Recommend = require('../models/recommend');

const { addMovieValidator, updateMovieValidator } = require('../validators/movieValidator');
const { idValidatorParam, idValidatorBody } = require('../validators/userValidator');
const { addArticleValidator } = require('../validators/articleValidator');
const { recommendValidator } = require('../validators/recommendValidator');
const auth = require('../middleware/authMiddleware');
const validate = require('../middleware/validatorMiddleware');



// 添加电影
router.post('/addMovie', addMovieValidator, validate, auth, async (req, res) => {
    // 判定用户的权限与状态
    const user = req.user;
    if (!user.isAdmin || !user.isActive) {
        return res.json({
            status: 1,
            message: '权限不足或用户已被封禁，请联系管理员'
        });
    };

    try {
        // 判断电影是否存在
        const movie = await Movie.findOne({ title: req.body.title });
        if (movie) {
            return res.json({
                status: 1,
                message: `电影${req.body.title}已存在`
            });
        }
        const { title, director, year, rating, downloadUrl, genre } = req.body;
        // 保存电影
        const newMovie = new Movie({
            title, director, year, rating, downloadUrl, genre
        });
        await newMovie.save();
        res.json({
            status: 0,
            message: '电影添加成功'
        });
    } catch (err) {
        console.log(err);
        res.json({
            status: 1,
            message: '服务器内部错误'
        });
    }
});

// 删除电影
router.delete('/deleteMovie/:id', idValidatorParam, validate, auth, async (req, res) => {
    const userId = req.user._id;
    const isAdmit = await User.adminAuth(userId);
    // 判定用户的权限与状态
    if (!isAdmit) {
        return res.json({
            status: 1,
            message: '权限不足，请联系管理员'
        });
    }
    try {
        const result = await Movie.deleteOne({ _id: req.params.id });
        if (result.deletedCount === 0) {
            return res.json({
                status: 1,
                message: '电影不存在'
            });
        }
        return res.json({
            status: 0,
            message: '电影删除成功'
        });
    } catch (err) {
        console.log(err);
        res.json({
            status: 1,
            message: '服务器内部错误'
        });
    }
});


// 更新电影
router.put('/updateMovie/', updateMovieValidator, validate, auth, async (req, res) => {
    const isAdmit = await User.adminAuth(req.user._id);
    // 判定用户的权限与状态
    if (!isAdmit) {
        return res.json({
            status: 1,
            message: '权限不足，请联系管理员'
        });
    }
    try {
        const id = req.body.id;
        const data = { ...req.body };
        console.log(data);
        const result = await Movie.updateOne({ _id: id }, { $set: data });
        if (result.modifiedCount === 0) {
            return res.json({
                status: 1,
                message: '电影不存在'
            });
        }
        return res.json({
            status: 0,
            message: '电影更新成功'
        });
    } catch (err) {
        console.log(err);
        res.json({
            status: 1,
            message: '服务器内部错误'
        });
    }
});

// 获取电影列表
router.get('/getMovieList', async (req, res) => {
    const result = await Movie.findAll();
    return res.json({ status: 0, data: result });
});

// 获取所有用户评论
router.get('/getUserComments', async (req, res) => {
    const result = await Comment.findAll();
    const cnt = result.length;
    return res.json({ status: 0, count: cnt, data: result });
});

// 审核用户评论
router.post('/checkComment', idValidatorBody, validate, auth, async (req, res) => {
    const isAdmit = await User.adminAuth(req.user._id);
    // 判定用户的权限与状态
    if (!isAdmit) {
        return res.json({
            status: 1,
            message: '权限不足，请联系管理员'
        });
    }
    try {
        const id = req.body.id;
        const comment = await Comment.findOne({ _id: id });
        if (!comment) {
            return res.json({
                status: 1,
                message: '评论不存在'
            });
        }
        comment.checked = true;
        await comment.save();
        return res.json({
            status: 0,
            message: '评论审核成功'
        });
    } catch (err) {
        console.log(err);
        res.json({
            status: 1,
            message: '服务器内部错误'
        });
    }
});

// 删除用户评论
router.delete('/deleteComment/:id', idValidatorParam, validate, auth, async (req, res) => {
    const isAdmit = await User.adminAuth(req.user._id);
    // 判定用户的权限与状态
    if (!isAdmit) {
        return res.json({
            status: 1,
            message: '权限不足，请联系管理员'
        });
    }
    try {
        const id = req.params.id;
        const result = await Comment.deleteOne({ _id: id });
        if (result.deletedCount === 0) {
            return res.json({
                status: 1,
                message: '评论不存在'
            });
        }
        return res.json({
            status: 0,
            message: '评论删除成功'
        });
    } catch (err) {
        console.log(err);
        res.json({
            status: 1,
            message: '服务器内部错误'
        });
    }
});

// 封禁用户
router.post('/banUser', idValidatorBody, validate, auth, async (req, res) => {
    // 判定用户的权限与状态
    const user = req.user;
    const isAdmit = await User.adminAuth(user._id);
    if (!isAdmit) {
        return res.json({
            status: 1,
            message: '权限不足，请联系管理员'
        });
    }
    try {
        const id = req.body.id;
        const user = await User.findById(id);
        if (!user) {
            return res.json({
                status: 1,
                message: '用户不存在'
            });
        }
        user.isActive = false;
        await user.save();
        return res.json({
            status: 0,
            message: '用户封禁成功'
        });
    } catch (err) {
        console.log(err);
        res.json({
            status: 1,
            message: '服务器内部错误'
        });
    }
});

// 解封用户 
router.post('/unbanUser', idValidatorBody, validate, auth, async (req, res) => {
    // 判定用户的权限与状态
    const user = req.user;
    const isAdmit = await User.adminAuth(user._id);
    if (!isAdmit) {
        return res.json({
            status: 1,
            message: '权限不足，请联系管理员'
        });
    }
    try {
        const id = req.body.id;
        const user = await User.findById(id);
        if (!user) {
            return res.json({
                status: 1,
                message: '用户不存在'
            });
        }
        user.isActive = true;
        await user.save();
        return res.json({
            status: 0,
            message: '用户解封成功'
        });
    } catch (err) {
        console.log(err);
        res.json({
            status: 1,
            message: '服务器内部错误'
        });
    }
});

// admin更新用户密码
router.post('/updatePassword', idValidatorBody, validate, auth, async (req, res) => {
    // 判定用户的权限与状态
    const isAdmit = await User.adminAuth(req.user._id);
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足，请联系管理员' });
    }
    try {
        const id = req.body.id;
        const password = req.body.password;
        if (password.length < 6) {
            return res.json({ status: 1, message: '密码长度不能小于6位' });
        }
        const user = await User.findById(id);
        if (!user) {
            return res.json({ status: 1, message: '用户不存在' });
        }
        user.password = password;
        await user.save();
        return res.json({ status: 0, message: '密码更新成功' });
    } catch (err) {
        console.log(err);
        res.json({ status: 1, message: '服务器内部错误' });
    }
});

// 显示所有用户信息
router.get('/getAllUsers', auth, async (req, res) => {
    const isAdmit = await User.adminAuth(req.user._id);
    // 判定用户的权限与状态
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足或者已经停用，请联系管理员' });
    }
    try {
        const users = await User.findAll();
        return res.json({ status: 0, message: '获取成功', data: users });
    } catch (err) {
        console.log(err);
        res.json({ status: 1, message: '服务器内部错误' });
    }
});

// 管理用户权限
router.post('/updateUserPermission', idValidatorBody, validate, auth, async (req, res) => {
    // 判定用户的权限与状态
    const isAdmit = await User.adminAuth(req.user._id);
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足，请联系管理员' });
    }
    try {
        const id = req.body.id;
        const user = await User.findById(id);
        if (!user) {
            return res.json({ status: 1, message: '用户不存在' });
        }
        user.isAdmin = req.body.permission;
        await user.save();
        return res.json({ status: 0, message: '权限更新成功' });
    } catch (err) {
        console.log(err);
        res.json({ status: 1, message: '服务器内部错误' });
    }
});

// 新增文章
router.post('/addArticle', addArticleValidator, validate, auth, async (req, res) => {
    // 判定用户的权限与状态
    const isAdmit = await User.adminAuth(req.user._id);
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足，请联系管理员' });
    }
    try {
        const { title, content, tags, status } = req.body;
        const newArticle = new Article({ title, content, tags, status, author: req.user.username });
        await newArticle.save();
        return res.json({ status: 0, message: '文章添加成功' });
    } catch (err) {
        console.log(err);
        res.json({ status: 1, message: '服务器内部错误' });
    }
});

// 删除文章 
router.delete('/deleteArticle', idValidatorBody, validate, auth, async (req, res) => {
    const isAdmit = await User.adminAuth(req.user._id);
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足或状态异常，请联系管理员' });
    }
    try {
        const article = await Article.deleteOne({ _id: req.body.id });
        if (article.deletedCount == 0) {
            return res.json({ status: 1, message: '文章不存在' })
        };
        return res.json({ status: 0, message: `编号为${req.body.id}的文章已被删除` });
    } catch (error) {
        console.error(error);
        return res.json({ status: 1, message: '服务器内容错误' });
    }
});

// 更新文章内容
router.put('/updateArticle', auth, async (req, res) => {
    const isAdmit = await User.adminAuth(req.user.id);
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足或状态异常，请联系管理员' });
    }
    try {
        const article = await Article.updateOne({ _id: req.body.id }, { $set: { content: req.body.content } });
        if (article.modifiedCount == 0) {
            return res.json({ status: 1, message: '文章不存在' })
        };
        console.log(article);
        return res.json({ status: 0, message: `编号为${req.body.id}的文章更新成功` });
    } catch (error) {
        console.error(error);
        return res.json({ status: 1, message: '服务器内容错误' })
    }
});

// 新增主页推荐
router.post('/addRecommend', recommendValidator, validate, auth, async (req, res) => {
    // 判定用户的权限与状态
    const isAdmit = await User.adminAuth(req.user._id);
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足，请联系管理员' });
    }
    try {
        const { imgUrl, title, detailUrl } = req.body;
        const newRecommend = new Recommend({ imgUrl, title, detailUrl });
        await newRecommend.save();
        return res.json({ status: 0, message: '推荐添加成功' });
    } catch (err) {
        console.log(err);
        res.json({ status: 1, message: '服务器内部错误' });
    }
});

// 删除主页推荐 
router.delete('/deleteRecommend', idValidatorBody, validate, auth, async (req, res) => {
    const isAdmit = await User.adminAuth(req.user._id);
    if (!isAdmit) {
        return res.json({ status: 1, message: '权限不足或状态异常，请联系管理员' });
    }
    try {
        const recommend = await Recommend.deleteOne({ _id: req.body.id });
        if (recommend.deletedCount == 0) {
            return res.json({ status: 1, message: '推荐不存在' })
        };
        return res.json({ status: 0, message: `编号为${req.body.id}的推荐已被删除` });
    } catch (error) {
        console.error(error);
        return res.json({ status: 1, message: '服务器内容错误' });
    }
});



module.exports = router;
